package com.youlai.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.common.util.RedisUtil;
import com.youlai.system.converter.TrendConfigConverter;
import com.youlai.system.helper.ApplicationContextHelper;
import com.youlai.system.mapper.TrendConfigMapper;
import com.youlai.system.model.entity.RedisNode;
import com.youlai.system.model.entity.TrendConfig;
import com.youlai.system.model.query.TrendConfigQuery;
import com.youlai.system.service.TrendConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TrendConfigServiceImpl extends ServiceImpl<TrendConfigMapper, TrendConfig> implements TrendConfigService {

    private final TrendConfigConverter trendConfigConverter;

    private final RedisUtil redisUtil;

    @Override
    public boolean deleteTrendConfig(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的用户数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return this.removeByIds(ids);
    }

    @Override
    public List<TrendConfig> getTrendByIds(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的用户数据为空");

        // 将字符串ID列表转换为Long列表
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());

        // 逐个获取TrendConfig对象
        List<TrendConfig> configs = new ArrayList<>();
        for (Long id : ids) {
            TrendConfig config = getById(id);
            if (config != null) {
                configs.add(config);
            }
        }

        return configs;
    }


    public Page<TrendConfig> getTrendConfigPage(TrendConfigQuery trendConfigQuery){

        int pageNum = trendConfigQuery.getPageNum();
        int pageSize = trendConfigQuery.getPageSize();
        String keywords = trendConfigQuery.getKeywords();
        Boolean enable = trendConfigQuery.getEnable();

        Page<TrendConfig> trendConfigPage = this.page(
                new Page<>(pageNum,pageSize),
                new LambdaQueryWrapper<TrendConfig>()
                        .like(StrUtil.isNotBlank(keywords),TrendConfig::getDescription,keywords)
                        .eq(TrendConfig::getEnable,enable)
        );

        Page<TrendConfig> pageResult =  trendConfigConverter.entity2Page(trendConfigPage);
        return pageResult;

    }

    @Override
    public TrendConfig getTrendConfigByAddress(String address) {
        return this.baseMapper.getTrendConfigByAddress(address);
    }

    @Override
    public boolean updateTrendConfig(TrendConfig trendConfig) {
        //更新到redis
        RedisNode redisNode = new RedisNode();
        redisNode.setTrendConfig(trendConfig);

        if(redisUtil.get(trendConfig.getAddress()) != null){
            redisUtil.delete(trendConfig.getAddress());
            redisUtil.set(trendConfig.getAddress(),redisNode,1, TimeUnit.DAYS);
        }else{
            redisUtil.set(trendConfig.getAddress(),redisNode,1, TimeUnit.DAYS);
        }
        return  updateById(trendConfig);
    }

    @Override
    public boolean deleteTrend(String ids) {
        //删除redis内容
        RedisUtil redisUtil = ApplicationContextHelper.getBean(RedisUtil.class);
        List<TrendConfig> trendConfigs = getTrendByIds(ids);
        try {
            for (TrendConfig item: trendConfigs){
                redisUtil.delete(item.getAddress());
            }
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
        return deleteTrendConfig(ids);
    }

    @Override
    public boolean saveTrendConfig(TrendConfig trendConfig) {

        //如果有先删除
        if(redisUtil.get(trendConfig.getAddress()) != null){
            redisUtil.delete(trendConfig.getAddress());
        }
        //添加redis内容
        RedisNode redisNode = new RedisNode();
        redisNode.setTrendConfig(trendConfig);
        redisUtil.set(trendConfig.getAddress(),redisNode,1, TimeUnit.DAYS);
        return save(trendConfig);
    }

    @Override
    public boolean saveTrendConfigList(List<TrendConfig> trendConfigList) {
        boolean allSucceeded = true;

        for (TrendConfig config : trendConfigList) {

            if(redisUtil.get(config.getAddress()) != null){
                redisUtil.delete(config.getAddress());
            }

            RedisNode redisNode = new RedisNode();
            redisNode.setTrendConfig(config);
            redisUtil.set(config.getAddress(),redisNode,1, TimeUnit.DAYS);

            if (!save(config)) {
                allSucceeded = false;
                break; // 如果有一个保存失败，则停止尝试保存剩余的配置
            }
        }

        return allSucceeded;
    }
}
